﻿#include "TabPage_dsn.h"
#include <QVBoxLayout>
#include <QMessageBox>

using namespace std;

void TabPage_dsn::fillData(ConfigUI* conf) {
	m_config = conf;
	// 2.将文件数据写入数据对象
	m_dataAcquired = m_parser->readFile(m_qFullName);
	if (!m_dataAcquired) return;
	m_runFinished = false;
	// 3.创建绘图窗口Diagram
	shared_ptr<DiagramData> diagramData = std::static_pointer_cast<DiagramData>(
		std::shared_ptr<Data_dsn>(m_data, [](auto*) {})); // 共享指针但不删除
	m_diagram = new Diagram(diagramData, m_config, this);
	m_algm = new AlgorithmLink_dsn(m_data, m_config);
	// 4.计算并绘制飞线
	if (m_data == nullptr) {
		QMessageBox::warning(this, "提示", "文件读取失败！");
	}
	m_algm->routingRunBegin();
	m_diagram->setData2();
	
	// 5.设置布局
	QVBoxLayout* layout = new QVBoxLayout(this);
	layout->setContentsMargins(0, 0, 0, 0);
	layout->addWidget(m_diagram);
	setLayout(layout);
	// 6.输出部分信息
	QPoint minPt = m_data->getMinPoint()->toPoint();
	QPoint maxPt = m_data->getMaxPoint()->toPoint();
	cout << "Min:(" << minPt.x() << ", " << minPt.y()<<"), Max:("<< maxPt.x() << ", " << maxPt.y() << ")" << endl;
}
void TabPage_dsn::refreshUI() {
	m_diagram->refresh();
}

//槽函数
void TabPage_dsn::pressRunButton() {
	m_algm->routingRun();
	m_diagram->setData2();
	refreshUI();
}
void TabPage_dsn::onConfigChanged() {
	const Style_dsn& sInfo = m_data->m_styleInfo;
	m_data->m_styles.getLineStyle(sInfo.flyLineKey)->setVisible(m_config->m_showFlyLines);
	for (const QString& key : sInfo.pathLineKeys) {
		m_data->m_styles.getLineStyle(key)->setVisible(m_config->m_showWires);
	}
	refreshUI();
}
void TabPage_dsn::tranformChanged() {
	m_diagram->initViewTransform();
	refreshUI();
}
void TabPage_dsn::leftPressRun(SelectedTarget* target) {
	if (target->lineSelected) {
		m_algm->pushLineRunBegin(target->sLine, *target->linesToRun);
	}
	else if (target->pinSelected) {
		m_algm->pushPinRunBegin(target->nearistPt, *target->linesToRun);
	}
}
void TabPage_dsn::leftPressMoveRun(SelectedTarget* target) {
	if (target->lineSelected) {
		m_algm->pushLineRun(target->offset, false, m_config->m_postOn);
	}
	else if (target->pinSelected) {
		m_algm->pushPinRun(target->offset, false);
	}
}
void TabPage_dsn::leftReleaseRun(SelectedTarget* target) {
	if (target->lineSelected) {
		m_algm->pushLineRun(target->offset, m_config->m_onGrids, m_config->m_postOn);
	}
	else if (target->pinSelected) {
		m_algm->pushPinRun(target->offset, m_config->m_onGrids);
	}
	m_diagram->setData1();
	m_diagram->setData2();
	refreshUI();
}